package com.apestech.framework.json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class JSONSerialization {
	
	private ByteArrayOutputStream os=new ByteArrayOutputStream();
	private int index=-1;
	
	public JSONSerialization() throws Exception{
		os.write("{".getBytes("UTF-8"));
	}
	
	public JSONSerialization(JSONObject obj) throws Exception{
		os.write("{".getBytes("UTF-8"));
		if(obj!=null){
			ArrayList<String> klist=obj.getKeylist();
			int len=obj.size();
			for(int i=0; i<len; i++){
				String key=klist.get(i);
				add(key, obj.get(key));
			}
		}
	}
	
	public void add(String key, Object value) throws Exception{
		if(value==null) return;
		this.index++;
		byte[] b;
		if(value.getClass().getName().equals("[B")){
			b=(byte[]) value;
		} else {
			b=JSON.toJSONByte(value);
		}
		if(this.index>0){
			os.write(",".getBytes("UTF-8"));
		}
		os.write(("\""+key+"\":").getBytes("UTF-8"));
		os.write(b,0,b.length);
	}

	public void add(String text) throws Exception {
		os.write(text.getBytes("UTF-8"));
	}

	public void add(JSONObject map) throws Exception {
		ArrayList<String> klist=map.getKeylist();
		int len=map.size();
		for(int i=0; i<len; i++){
			String key=klist.get(i);
			add(key, map.get(key));
		}
	}
	
	public void fini() throws IOException{
		os.write("}".getBytes("UTF-8"));
	}
	
	public byte[] getBytes(){
		return os.toByteArray();
	}
	
	public String toString(){
		return os.toString();
	}

	public void close() throws Exception {
		os.flush();
		os.close();
	}

}
